from BeautifulSoup import BeautifulSoup as bs
import cookielib
import re
import sys
import urllib
import urllib2

username = None
password = None

def setupLogin():
	global username, password
	username, password = sys.argv[1].split(':')

def findTorrentTable(tag):
	if tag.name != 'table':
		return False
	for k, v in tag.attrs:
		if k == 'id' and v == 'torrent_table':
			return True
	return False
	
def findTorrentRows(tag):
	if tag.name != 'tr':
		return False
	for k, v in tag.attrs:
		if k == 'class' and v in v.split():
			return True
	return False

removeFirstTag = re.compile(r'(.*)<.*>(.*)$')
removeTags = re.compile(r'<.*?>')

def splitRows(tag, showTags):
#	print 'Argument is of type:', str(tag.__class__)
	try:
		rows = tag.contents
	except AttributeError:
		print 'Attribute error, type:', str(tag.__class__)
		return []
	rows = [str(x) for x in rows if x != '\n']
#	print 'Preliminary rows'
#	for row in rows:
#		print '*', row
	if showTags:
		return rows
	processed = []
	for row in rows:
		row = removeTags.sub('', row)
		processed.append(row)
#		while row.index('>') != -1:
#			m = removeFirstTag.
#		processed.append(row)
#		r = What.splitRows(a.findAll('tr')[0], False)
#		endClipped = row[:-len('</td>')]
#		if endClipped.startswith('<td>'):
#			processed.append(endClipped[len('<td>'):])
#			continue
#		try:
#			processed.append(endClipped[endClipped.index('>') + 1:])
#		except ValueError:
#			print 'Failed:', processed
	return processed

class Parser:
	pass

class WhatParser(Parser):
	def __init__(self):
		print 'What parser initialized'
		self.login_url = 'http://what.cd/login.php'
		self.cj = cookielib.CookieJar()
		self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
		self.bs = None
	
	def getFullDocument(self):
		return self.bs
		
		
	def login(self, username, password):
		print 'Username:', username
		print 'Password:', '*' * len(password)
		
		page = self.opener.open(self.login_url, urllib.urlencode({'username':username, 'password':password}))
		
		self.bs = bs(page.read())
		
	def search(self, search_string):
		url = 'http://what.cd/torrents.php?searchstr=%s&order_by=time&order_way=desc' % (search_string,)
#		return bs(self.opener.open(url).read())
		return bs(self.opener.open(url).read()).findAll(findTorrentTable)[0];
		
#		url = 'http://what.cd/torrents.php?searchstr=&taglist=country&tags_type=1&order_by=time&order_way=desc'
#		url = 'http://what.cd/torrents.php?searchstr=&taglist=country&tags_type=1&order_by=time&order_way=desc'
#		url = '&filter_cat%5B1%5D=1&filter_cat%5B2%5D=1&filter_cat%5B3%5D=1&filter_cat%5B4%5D=1&filter_cat%5B5%5D=1&filter_cat%5B6%5D=1&filter_cat%5B7%5D=1'
	def isLoggedIn(self):
		pass

	def monitor(self):
#		url = 'http://what.cd'
		pass

def soup():
	setupLogin()
	w = WhatParser()
	w.login(username, password)
	return w.bs

def search():
	setupLogin()
	w = WhatParser()
	w.login(username, password)
	return w.search('good')
	
def main():
	setupLogin()
	w = WhatParser()
	w.login(username, password)
	a = w.search('good')
	cleanedUp = []
	for row in a.contents:
		cleanedUp.append(splitRows(row, False))
	return cleanedUp
		
if __name__ == '__main__':
	main()
